import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import { Skin } from 'src/utils/skinVars';
import { Spin } from 'antd';

function SkinProvider(props) {
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    setLoading(true);
    // 第一次进来，先请求skin
    props.dispatch({ type: 'skin/querySkinInfo', params: {} }).then(() => {
      setLoading(false);
      // 设置skin
      setSkin();
    });
  }, []);

  useEffect(() => {
    setSkin();
  }, [props.skin_color]);
  useEffect(() => {
    setSkin();
  }, [props.font_color]);
  useEffect(() => {
    setSkin();
  }, [props.primary_color]);

  useEffect(() => {
    setSkin();
  }, [props.location.pathname]);

  function setSkin() {
    if (
      props.skin_preview.skin_color === props.skin_color &&
      props.skin_preview.font_color === props.font_color &&
      props.skin_preview.primary_color === props.primary_color
    ) {
      return;
    }
    const skin = new Skin({
      skinColor: props.skin_color,
      fontColor: props.font_color,
      prColor: props.primary_color,
    });

    skin.changeLess();
    props.dispatch({
      type: 'skin/updatePreview',
      data: {
        skin_color: props.skin_color,
        font_color: props.font_color,
        primary_color: props.primary_color,
      },
    });
  }
  return (
    <>
      {!loading ? (
        props.children
      ) : (
        <div className='skin-loading'>
          <Spin size='large' tip='Loading...' spinning={loading} />
        </div>
      )}
    </>
  );
}
function mapStateToProps(state) {
  const { skin_preview, ...skinOther } = state.skin;
  return {
    ...skinOther,
    skin_preview: skin_preview,
  };
}
export default connect(mapStateToProps)(SkinProvider);
